<template>
  <div class="search">
    <el-autocomplete
      v-model="state"
      :fetch-suggestions="querySearchAsync"
      placeholder="请输入菜品名称"
      @select="handleSelect"
    >
      <i class="el-icon-edit el-input__icon" slot="suffix"></i>
    </el-autocomplete>
    <!-- <el-button
      :style="{ left: 10 + 'px' }"
      type="primary"
      plain
      class="btn1"
      @click="query"
      >查询</el-button
    > -->
    <el-button type="primary" plain @click="addData()">新增菜品</el-button>
    <el-button type="primary" plain @click="reset">重置</el-button>
    <el-table style="width: 100%" :data="elTableData">
      <el-table-column
        prop="id"
        label="菜品ID"
        min-width="100"
      ></el-table-column>
      <el-table-column
        prop="food_name"
        label="菜品名称"
        min-width="100"
      ></el-table-column>
      <el-table-column prop="food_action" label="使用状态" min-width="100">
        <template slot-scope="scope">
          <el-switch
            :validate-event="true"
            :active-value="1"
            :inactive-value="0"
            v-model="scope.row.food_action"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        prop="food_price"
        label="菜品价格"
        min-width="100"
      ></el-table-column>
      <el-table-column
        prop="food_type"
        label="菜品类型"
        min-width="100"
      ></el-table-column>
      <el-table-column label="图片预览" min-width="100">
        <template slot-scope="scope">
          <img
            :src="imgUrl + scope.row.food_img"
            alt=""
            style="width: 80px; height: 60px"
          />
        </template>
      </el-table-column>

      <el-table-column prop="date" label="操作" min-width="180">
        <template slot-scope="scope">
          <el-button type="primary" @click="revise(scope.row)">修改</el-button>
          <el-button type="danger" @click="delFood(scope.row)"
            >删除菜品</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="elPage"
      @current-change="ChangePage"
      :page-size="5"
      layout="prev, pager, next"
      :total="tableData.length"
    >
    </el-pagination>
    <!-- 修改,新增的的弹出框 -->
    <el-dialog title="修改菜品" :visible.sync="dialogFormVisible" width="30%">
      <el-form :model="form">
        <el-form-item
          v-if="isEdit"
          label="菜品ID"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="form.id"
            autocomplete="off"
            name="id"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="菜品名称" :label-width="formLabelWidth">
          <el-input
            v-model="form.food_name"
            name="food_name"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item
          v-if="!isEdit"
          label="菜品图片"
          :label-width="formLabelWidth"
        >
          <el-upload
            name="uploadImg"
            class="avatar-uploader"
            action="/api/addFood"
            :on-success="successImg"
            :before-upload="beforeAvatarUpload"
            :show-file-list="false"
            :auto-upload="false"
            :data="form"
            ref="upimg"
          >
            <img v-if="imgPath" :src="imgPath" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="菜品价格" :label-width="formLabelWidth">
          <el-input
            v-model="form.food_price"
            name="food_price"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          v-if="isEdit"
          label="菜品状态"
          :label-width="formLabelWidth"
        >
          <el-switch
            :active-value="1"
            :inactive-value="0"
            v-model.number="form.food_action"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="菜品类型" :label-width="formLabelWidth">
          <el-select
            v-model="form.food_type"
            name="food_type"
            placeholder="请选择菜品类型"
          >
            <el-option
              v-for="item in tableData"
              :key="item.id"
              :label="item.food_type"
              :value="item.food_type"
              >{{ item.food_type }}</el-option
            >
          </el-select>
        </el-form-item>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="fromSave()">确 定</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import * as api from "../utils/api";
export default {
  data() {
    name: "comm";
    return {
      restaurants: [],
      state: "",
      timeout: null,
      tableData: [] /* 装所有菜品的数组 */,
      imgUrl: "http://101.37.146.52:3000/",
      value: 1,
      elPage: 1 /* 当前页码 */,
      timeout: null,
      itemTableData: [] /* 点查询按钮搜索装的值 */,
      // dialogTableVisible: false,
      dialogFormVisible: false,

      form: {
        id: "",
        food_name: "",
        food_action: "",
        food_price: "",
        food_type: "",
        // type: [],
        // resource: "",
        // desc: "",
      },
      formLabelWidth: "120px",
      isEdit: true,
      imgPath: "",
    };
  },
  computed: {
    /* 当页面渲染的数据 */
    dangqianPage() {
      let dangqianNum = (this.dangqianyema - 1) * 5;
      let dangqianPageData = this.tableData.slice(dangqianNum, dangqianNum + 5);
      return dangqianPageData;
    },
    /* 一共有多少页 */
    pageNum() {
      return Math.ceil(this.tableData.length / 5);
    },
    // 每页多少条数据
    elTableData() {
      let kaishi = (this.elPage - 1) * 5;
      let jieshu = (this.elPage - 1) * 5 + 5;
      return this.tableData.slice(kaishi, jieshu);
    },
  },
  methods: {
    successImg(resp, file, fileList) {
      if (resp.code == 200) {
        // console.log(123);
        this.$message({
          type: "success",
          message: resp.msg,
        });
        this.dialogFormVisible = false;
        this.commTableData();
        this.form = {}
      }
    },
    commTableData() {
      this.axios({
        url: api.GET_COMM,
        method: "get",
        // params:{

        // }
      }).then((data) => {
        for (let i of data.data.data) {
          i.value = i.food_name;
        }
        this.tableData = data.data.data;
        // console.log(data);
      });
    },
    loadAll() {
      return this.tableData;
    },
    //queryString 为在框中输入的值
    //cb 回调函数,将处理好的数据推回
    querySearchAsync(queryString, cb) {
      var restaurants = this.tableData;
      var results = queryString
        ? restaurants.filter(this.createStateFilter(queryString))
        : restaurants;
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 1000 * Math.random());
    },
    createStateFilter(queryString) {
      return (state) => {
        return (
          state.value.toLowerCase().indexOf(queryString.toLowerCase()) != -1
        );
      };
    },
    // 点搜索框直接查询数据
    handleSelect(item) {
      return (this.tableData = [item]);
    },
    mounted() {
      this.restaurants = this.loadAll();
    },
    // 点查询搜索
    query() {
      console.log(123);
    },
    // 重置按钮
    reset() {
      this.state = "";
      return (
        this.commTableData((this.id = this.tableData.id)),
        (this.food_name = this.tableData.food_name),
        (this.food_action = this.tableData.food_action),
        (this.food_price = this.tableData.food_price),
        (this.food_img = this.tableData.food_img)
      );
    },
    // 使用状态按钮
    changeSwitch() {
      console.log(123);
    },
    ChangePage(val) {
      // console.log(val);
      this.elPage = val;
    },
    // elPage() {},
    // 修改按钮
    revise(rowData) {
      this.form = Object.assign({}, rowData);
      this.dialogFormVisible = true;
      this.isEdit = true;
    },
    // 新增菜品按钮
    addData() {
      this.form = {}
      this.isEdit = false;
      this.dialogFormVisible = true;
    },
    // 确定修改
    fromSave() {
      if (this.isEdit) {
        console.log(this.form);
        this.axios({
          url: api.POST_UPLOAD,
          method: "post",
          data: {
            id: this.form.id,
            food_name: this.form.food_name,
            food_action: this.form.food_action,
            food_price: this.form.food_price,
            food_type: this.form.food_type,
          },
        }).then((data) => {
          if (data.data.code == 200) {
            this.$message({
              type: "success",
              message: data.data.msg,
            });
            this.dialogFormVisible = false;
            this.commTableData();
            this.form = {}
          } else {
            this.$message({
              type: "error",
              message: data.data.msg,
            });
          }
        });
      } else {
        this.$refs.upimg.submit()
        // console.log(this.$refs.upimg);
      }
    },
    // 上传图片
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
    // 删除按钮
    delFood(rowData) {
      // console.log(rowData);
      let delFoodData = rowData
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return this.delCreate(delFoodData)
        console.log(delFoodData);
        if (delFoodData != '') {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }
        this.commTableData();
      }).catch((err) => {
        console.log(err);
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 删除方法
    delCreate(obj) {
      if (obj.food_action) {
        alert('菜品正在使用中，不能删除')
        return
      } else {
        return this.axios({
          url: api.POST_DELETEFOOD,
          method: "post",
          data: {
            id: obj.id,
          },
        }).then((data) => {
          console.log(data);
        }).catch(err => {
          console.log(err);
        })
      }
    }
  },
  created() {
    this.commTableData();
  },
};
</script>

<style lang='less'>
.search {
  margin-top: 15px;
  text-align: justify;
}
.el-autocomplete {
  margin-right: 10px;
}
.el-pagination {
  text-align: center;
}
.el-table {
  margin-top: 15px;
  border-radius: 10px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.dialog-footer {
  text-align: center;
}
</style>